import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import javax.swing.JFrame;


public class Sound extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected boolean running;


	public Sound(){
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container content = getContentPane();
		final JButton record = new JButton("Start");
		record.setEnabled(true);
		
		ActionListener captureListener = new ActionListener() 
		{
		      public void actionPerformed(ActionEvent e) {
		      
		        record.setEnabled(false);
		        running=true;
		        Record();
		       		       
		    }};
		    record.addActionListener(captureListener);
		    content.add(record, BorderLayout.CENTER
		    		);	
		 }
		
	public void Record()
	{
		try {

			final AudioFormat format = getFormat(); //Fill AudioFormat with the wanted settings
			DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
			final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
			line.open(format);
			line.start();
			
			OutputStream out = new ByteArrayOutputStream();
			
			int bufferSize = (int)format.getSampleRate()*format.getFrameSize();
			byte buffer[] = new byte[bufferSize];
			try {
				int c = 0;
				while (running) {
			        int count = line.read(buffer, 0, buffer.length);
			        if (count > 0) {
			            out.write(buffer, 0, count);
			        }
			        if (c++<1000000) {
			        	running = false;
			        }	        
			    }
			    out.close();
			} catch (IOException e) {
			    System.err.println("I/O problems: " + e);
			    System.exit(-1);
			}

			for (byte b : buffer) {
				System.out.print(b+ " ");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static AudioFormat getFormat() {
	    float sampleRate = 44100;
	    int sampleSizeInBits = 8;
	    int channels = 2; 
	    boolean signed = true;
	    boolean bigEndian = true;
	    return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
	}

	
	public static void main(String[] args) {

	    JFrame frame = new Sound();
	    frame.setSize(200,500);
	    frame.setTitle("Play!");
	    frame.setLocation(500,300);
	    frame.setVisible(true);
	    frame.pack();
			
		
	}
	
}
